package com.example.netchat;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.example.netchat.ContentUtils.Room;

public class ChatFragment extends Fragment implements
		LoaderManager.LoaderCallbacks<Cursor> {
	public interface ActionListener {
		void onRoomDelete();
	}

	public static final String ARGUMENT_ROOM_ID = "room_id";
	private Context mContext;
	private final BroadcastReceiver mIncomingMessageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getStringExtra(ChatService.ROOM_ID_EXTRA).equals(
					getArguments().getString(ARGUMENT_ROOM_ID))) {
				this.setResult(Activity.RESULT_OK, null, null);
			}
		}
	};
	private SimpleCursorAdapter mAdapter;
	private Room room;
	private BroadcastReceiver mRoomDeletedReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (ChatFragment.this.room != null
					&& intent.getLongExtra(ChatService.ID_EXTRA, 0) == ChatFragment.this.room._id) {
				((ChatFragment.ActionListener) getActivity()).onRoomDelete();
			}
		}
	};
	private ListView mListView;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		mContext = activity.getApplicationContext();
	}

	@Override
	public void onResume() {
		super.onResume();

		mContext.registerReceiver(mIncomingMessageReceiver, new IntentFilter(
				ChatService.HANDLE_INCOMING_MESSAGE_ACTION));
		mContext.registerReceiver(mRoomDeletedReceiver, new IntentFilter(
				ChatService.ROOM_DELETED_ACTION));
	}

	@Override
	public void onPause() {
		mContext.unregisterReceiver(mIncomingMessageReceiver);
		mContext.unregisterReceiver(mRoomDeletedReceiver);

		super.onPause();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_chat, null);

		mListView = (ListView) view.findViewById(R.id.messages_listview);

		this.room = ContentUtils.getRoomByRoomId(getActivity(), getArguments()
				.getString(ARGUMENT_ROOM_ID));

		final TextView textView = (TextView) view.findViewById(R.id.chat_entry);

		view.findViewById(R.id.send_button).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View view) {
						sendMessage(room, textView);
					}

				});

		mAdapter = new SimpleCursorAdapter(
				mContext,
				R.layout.listitem_message,
				null,
				new String[] {
						MessagesContentProvider.ALL_COLUMNS[MessagesContentProvider.MESSAGE_COLUMN_INDEX],
						MessagesContentProvider.ALL_COLUMNS[MessagesContentProvider.FROM_COLUMN_INDEX] },
				new int[] { android.R.id.text1, android.R.id.text2 }, 0);

		mListView.setAdapter(mAdapter);

		return view;
	}

	private void sendMessage(final Room room, final TextView textView) {
		String message = textView.getText().toString();
		String nick = PreferenceManager.getDefaultSharedPreferences(
				this.getActivity().getApplicationContext()).getString(
				CommonUtilities.NICK_PREF, "anon");

		getActivity().startService(
				ChatService.createSendMessageIntent(getActivity(),
						room.room_id, message, nick));

		textView.setText("");
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		getLoaderManager().initLoader(0, null, this);
	}

	public Loader<Cursor> onCreateLoader(int id, Bundle args) {

		Uri baseUri = MessagesContentProvider.CONTENT_URI;

		String where = MessagesContentProvider.ALL_COLUMNS[MessagesContentProvider.ROOM_ID_COLUMN_INDEX]
				+ "=?";
		String[] whereArgs = new String[] { room.room_id };

		return new CursorLoader(
				getActivity(),
				baseUri,
				MessagesContentProvider.ALL_COLUMNS,
				where,
				whereArgs,
				MessagesContentProvider.ALL_COLUMNS[MessagesContentProvider.DATETIME_COLUMN_INDEX]
						+ " ASC");
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		if (data != null) {
			data.setNotificationUri(getActivity().getContentResolver(),
					MessagesContentProvider.CONTENT_URI);
		}

		mAdapter.swapCursor(data);

		if (data != null) {
			final int pos = data.getCount();
			mListView.post(new Runnable() {
				@Override
				public void run() {
					mListView.smoothScrollToPosition(pos);
				}
			});
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		mAdapter.swapCursor(null);
	}
}
